package com.example.demo.connect;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log;

import java.lang.reflect.Method;
import java.util.Set;

public class ConnectManager {

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothProfile a2dpProfile;
    private BluetoothProfile hfpProfile;
    private BluetoothDevice bluetoothDevice;

    public ConnectManager(BluetoothAdapter adapter, String deviceAddress) {
        this.bluetoothAdapter = adapter;
        this.bluetoothDevice = findBluetoothDevice(deviceAddress);
    }

    /**
     * 根据设备地址查找蓝牙设备
     *
     * @param deviceAddress 目标蓝牙设备的地址
     * @return 如果找到匹配的设备，则返回BluetoothDevice对象；否则返回null
     */
    @SuppressLint("MissingPermission")
    private BluetoothDevice findBluetoothDevice(String deviceAddress) {
        // 获取已配对的蓝牙设备集合
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

        // 遍历已配对的设备，寻找目标设备
        for (BluetoothDevice device : pairedDevices) {
            // 比较设备地址，找到目标设备则返回
            if (device.getAddress().equals(deviceAddress)) {
                return device;
            }
        }

        // 未找到目标设备，返回null
        return null;
    }


    // 初始化 A2DP 和 HFP 配置文件
    @SuppressLint("MissingPermission")
    public void initProfiles(Context context) {
        // 创建 A2DP 配置文件代理
        bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                // 当连接到 A2DP 配置文件时，保存代理对象
                if (profile == BluetoothProfile.A2DP) {
                    a2dpProfile = proxy;
                }
                // 当连接到 HFP 配置文件时，保存代理对象
                else if (profile == BluetoothProfile.HEADSET) {
                    hfpProfile = proxy;
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
                // 当 A2DP 配置文件断开连接时，清除代理对象
                if (profile == BluetoothProfile.A2DP) {
                    a2dpProfile = null;
                }
                // 当 HFP 配置文件断开连接时，清除代理对象
                else if (profile == BluetoothProfile.HEADSET) {
                    hfpProfile = null;
                }
            }
        }, BluetoothProfile.A2DP);

        // 创建 HFP 配置文件代理
        bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                // 当连接到 HFP 配置文件时，保存代理对象
                if (profile == BluetoothProfile.HEADSET) {
                    hfpProfile = proxy;
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
                // 当 HFP 配置文件断开连接时，清除代理对象
                if (profile == BluetoothProfile.HEADSET) {
                    hfpProfile = null;
                }
            }
        }, BluetoothProfile.HEADSET);
    }


    // 连接逻辑
    @SuppressLint("MissingPermission")
    public void connectDevice(Runnable onSuccess) {
        if (bluetoothDevice == null) {
            Log.e("Bluetooth", "蓝牙设备为空");
            return;
        }

        if (a2dpProfile != null && a2dpProfile instanceof BluetoothA2dp) {
            BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) a2dpProfile;
            try {
                Method connectMethod = BluetoothA2dp.class.getMethod("connect", BluetoothDevice.class);
                connectMethod.invoke(bluetoothA2dp, bluetoothDevice);
                Log.d("Bluetooth", "A2DP 连接请求已发送");
            } catch (Exception e) {
                Log.e("Bluetooth", "无法调用 A2DP 的 connect 方法", e);
            }
        }

        if (hfpProfile != null && hfpProfile instanceof BluetoothHeadset) {
            BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) hfpProfile;
            try {
                Method connectMethod = BluetoothHeadset.class.getMethod("connect", BluetoothDevice.class);
                connectMethod.invoke(bluetoothHeadset, bluetoothDevice);
                Log.d("Bluetooth", "HFP 连接请求已发送");
            } catch (Exception e) {
                Log.e("Bluetooth", "无法调用 HFP 的 connect 方法", e);
            }
        }

        if (onSuccess != null) {
            onSuccess.run();
        }
    }

    // 断开连接
    @SuppressLint("MissingPermission")
    public void disconnectDevice(Runnable onSuccess) {
        if (bluetoothDevice == null) {
            Log.e("Bluetooth", "蓝牙设备为空");
            return;
        }

        if (a2dpProfile != null && a2dpProfile instanceof BluetoothA2dp) {
            BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) a2dpProfile;
            try {
                Method disconnectMethod = BluetoothA2dp.class.getMethod("disconnect", BluetoothDevice.class);
                disconnectMethod.invoke(bluetoothA2dp, bluetoothDevice);
                Log.d("Bluetooth", "A2DP 断开请求已发送");
            } catch (Exception e) {
                Log.e("Bluetooth", "无法调用 A2DP 的 disconnect 方法", e);
            }
        }

        if (hfpProfile != null && hfpProfile instanceof BluetoothHeadset) {
            BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) hfpProfile;
            try {
                Method disconnectMethod = BluetoothHeadset.class.getMethod("disconnect", BluetoothDevice.class);
                disconnectMethod.invoke(bluetoothHeadset, bluetoothDevice);
                Log.d("Bluetooth", "HFP 断开请求已发送");
            } catch (Exception e) {
                Log.e("Bluetooth", "无法调用 HFP 的 disconnect 方法", e);
            }
        }

        if (onSuccess != null) {
            onSuccess.run();
        }
    }

    // 检查连接状态
    @SuppressLint("MissingPermission")
    public boolean isConnected() {
        boolean a2dpConnected = false;
        boolean hfpConnected = false;

        if (a2dpProfile != null && a2dpProfile instanceof BluetoothA2dp) {
            BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) a2dpProfile;
            if (bluetoothA2dp.getConnectionState(bluetoothDevice) == BluetoothProfile.STATE_CONNECTED) {
                a2dpConnected = true;
            }
        }

        if (hfpProfile != null && hfpProfile instanceof BluetoothHeadset) {
            BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) hfpProfile;
            if (bluetoothHeadset.getConnectionState(bluetoothDevice) == BluetoothProfile.STATE_CONNECTED) {
                hfpConnected = true;
            }
        }

        return a2dpConnected || hfpConnected;
    }

    // 检查断开状态
    @SuppressLint("MissingPermission")
    public boolean isDisconnected() {
        boolean a2dpDisconnected = false;
        boolean hfpDisconnected = false;

        if (a2dpProfile != null && a2dpProfile instanceof BluetoothA2dp) {
            BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) a2dpProfile;
            if (bluetoothA2dp.getConnectionState(bluetoothDevice) == BluetoothProfile.STATE_DISCONNECTED) {
                a2dpDisconnected = true;
            }
        }

        if (hfpProfile != null && hfpProfile instanceof BluetoothHeadset) {
            BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) hfpProfile;
            if (bluetoothHeadset.getConnectionState(bluetoothDevice) == BluetoothProfile.STATE_DISCONNECTED) {
                hfpDisconnected = true;
            }
        }

        return a2dpDisconnected && hfpDisconnected;
    }

}
